import { Bus, BusDetail } from '@/apis/bus';
import { getUserInfo } from '@/apis/user';
import Title from '@/assets/loading-1.png';
import LoadingEnding from '@/assets/loading-2.png';
import LoadingBus from '@/assets/loading-3.png';
import Bus2 from '@/assets/loading-4.png';
import Bus1 from '@/assets/loading-5.png';
import Bg from '@/assets/loading-bg.jpg';
import { PreLoadImages } from '@/utils';
import '@animxyz/core';
import { XyzTransitionGroup } from '@animxyz/react';
import delay from 'delay';
import FakeProgress from 'fake-progress';
import { useEffect, useRef, useState } from 'react';
import { history, useQuery, useSearchParams } from 'umi';

const requireContext = require.context(
  '../assets',
  true,
  /\.|png|jpg|svg|webp$/,
);
const requireAll = (context: any) => context.keys().map(context);
const images = requireAll(requireContext);

const p = new FakeProgress({
  timeConstant: 10000,
  autoStart: true,
});

export default function Page() {
  const [progress, setProgress] = useState<number>(0);
  const timeout = useRef<NodeJS.Timeout>();

  const [searchParams] = useSearchParams();

  // #分享进入的参数
  const reStart = Boolean(searchParams.get('restart'));
  const busId = searchParams?.get('busId');

  // *分享模式下， 走这里的逻辑
  useQuery(['bus:detail'], () => BusDetail({ id: busId! }), {
    enabled: !!busId,
    onSuccess: async function (data) {
      await handleEnd();
      const localUserId = localStorage.getItem('userId');
      // ?是否是自己发的车
      if (data.user_id && `${data?.user_id}` === localUserId) {
        history.replace(
          data?.passengers?.length === 2
            ? `/success?busId=${data.id}`
            : `/waiting?busId=${data.id}`,
        );
        return;
      }

      // ? 还有座位
      if (data?.passengers?.length < 2) {
        return history.replace(`/join?busId=${data.id}`);
      }

      // ?没有座位了, 满员
      history.replace(`/join/complate?busId=${data.id}`);
    },
  });

  // *正常走这里
  useQuery(['my:bus'], () => Bus(), {
    enabled: !busId,
    onSuccess: async function (data) {
      await PreLoadImages(images);
      await handleEnd();

      // *发过车吗?
      if (data?.length) {
        // ?有正在拼的吗
        const find = data?.find((i) => i.num < 2);
        history.replace(
          find
            ? `/waiting?busId=${find.id}`
            : reStart
            ? '/introduce'
            : `/success?busId=${data[0]?.id}`, // *如果没有找到正在拼的车， 那就进入完成页
        );

        return;
      }

      history.replace('/introduce');
    },
  });

  useQuery(['get:user'], getUserInfo);
  useEffect(() => {
    timeout.current = setInterval(() => {
      setProgress(Math.round(p.progress * 100));
    }, 1000);
  }, []);

  // *结束
  async function handleEnd() {
    clearInterval(timeout.current);
    p.end();

    await delay(500);
    setProgress(100);
    return await delay(500);
  }

  return (
    <XyzTransitionGroup
      appear
      appearVisible
      xyz="fade up-2 appear-stagger"
      className=" min-h-screen bg-black bg-cover bg-bottom overflow-hidden relative flex items-center flex-col pt-[120px]"
      style={{
        backgroundImage: `url(${Bg})`,
      }}
    >
      {/* title */}
      <h1
        className=" w-[652px] h-[278px] bg-cover relative left-[20px]"
        style={{ backgroundImage: `url(${Title})` }}
      />

      {/* loading bar */}
      <div className="mt-[200px] relative w-[570px] h-2 bg-[rgba(255,255,255,.7)] rounded-full border-2 border-solid border-white flex justify-end">
        <i
          className="w-[52px] h-[60px] bg-cover absolute left-[4px]  bottom-[12px]"
          style={{
            backgroundImage: `url(${LoadingEnding})`,
          }}
        ></i>
        <span
          className=" bg-[#1e7842] h-full  block rounded-full relative transition-all"
          style={{
            width: `${progress}%`,
          }}
        >
          <i
            className="w-[156px] h-[60px] bg-cover absolute -left-[10px] bottom-[10px]"
            style={{
              backgroundImage: `url(${LoadingBus})`,
            }}
          ></i>
        </span>
      </div>

      {/* bus */}
      <b
        xyz="fade right-5 delay-4"
        className="w-[574px] h-[260px] absolute left-0  bottom-[280px] bg-cover"
        style={{ backgroundImage: `url(${Bus1})` }}
      ></b>
      <b
        xyz="fade right-5"
        className="w-[574px] h-[374px] absolute left-[210px] bottom-[210px] bg-cover"
        style={{ backgroundImage: `url(${Bus2})` }}
      ></b>
    </XyzTransitionGroup>
  );
}
